﻿using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;

namespace Utility
{
	/// <summary>
	/// 枚举工具
	/// </summary>
	public class EnumHelper
	{
		/// <summary>
		/// 获取枚举的所有枚举项
		/// </summary>
		/// <typeparam name="T">枚举类型</typeparam>
		/// <returns></returns>
		public static T[] GetEnums<T>()
		{
			if (!typeof(T).IsEnum)
			{
				throw new InvalidOperationException("typeparam T must be Enum");
			}
			return (T[])Enum.GetValues(typeof(T));
		}

		/// <summary>
		/// 获取枚举中值大于0的枚举项
		/// </summary>
		/// <typeparam name="T">枚举类型</typeparam>
		/// <returns></returns>
		public static T[] GetPositiveEnums<T>()
		{
			if (!typeof(T).IsEnum)
			{
				throw new InvalidOperationException("typeparam T must be Enum");
			}
			List<T> enumList = new List<T>();
			Array values = Enum.GetValues(typeof(T));
			foreach (object value in values)
			{
				if ((int)value > 0) enumList.Add((T)value);
			}
			return enumList.ToArray();
		}

		/// <summary>
		/// 获取枚举项的DescriptionAttribute声明的描述
		/// </summary>
		/// <typeparam name="T">枚举类型</typeparam>
		/// <param name="enumItem"></param>
		/// <returns></returns>
		public static string GetEnumItemDescription<T>(T enumItem)
		{
			if (!enumItem.GetType().IsEnum)
			{
				throw new InvalidOperationException("typeparam T must be Enum");
			}
			object[] attributes = enumItem.GetType().GetField(enumItem.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
			string desc;
			if (attributes.Length > 0)
				desc = (attributes[0] as DescriptionAttribute).Description;
			else
				desc = enumItem.ToString();
			return desc;
		}

		private EnumHelper() { }
	}
}
